﻿using AutoMapper;
using CK.Sprite.Framework;
using JetBrains.Annotations;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CK.Sprite.Form.Core
{
    public class SpriteObjectLocalCache : LocalCache<SpriteObjectDto>
    {
        public override string CacheKey => CommonConsts.SpriteObjectCacheKey;

        public override List<SpriteObjectDto> GetAll(string applicationCode)
        {
            if (!LocalCacheContainer.IsEnabledLocalCache)
            {
                return _serviceProvider.DoDapperService(DefaultDbConfig, (unitOfWork) =>
                {
                    return GetSpriteObjectDtos(applicationCode, unitOfWork);
                });
            }
            else
            {
                return (List<SpriteObjectDto>)LocalCacheContainer.Get($"{applicationCode}_{CacheKey}", key =>
                {
                    return _serviceProvider.DoDapperService(DefaultDbConfig, (unitOfWork) =>
                    {
                        return GetSpriteObjectDtos(applicationCode, unitOfWork);
                    });
                });
            }
        }

        private List<SpriteObjectDto> GetSpriteObjectDtos(string applicationCode, IUnitOfWork unitOfWork)
        {
            var spriteObjectRepository = ConnectionFactory.GetConnectionProvider(DefaultDbConfig.ConnectionType).GetRepository<ISpriteObjectRepository>(unitOfWork);
            var spriteObjects = spriteObjectRepository.GetAllSpriteObjectByApplicationCode(applicationCode);
            List<SpriteObjectDto> spriteObjectDtos = Mapper.Map<List<SpriteObjectDto>>(spriteObjects);

            spriteObjectDtos.ForEach(r =>
            {
                var spriteObject = spriteObjects.First(t => t.Id == r.Id);
                r.ObjectPropertyDtos = SerializeService.DeserializeObject<List<ObjectPropertyDto>>(spriteObject.PropertyJsons);
            });

            return spriteObjectDtos;
        }
    }
}
